﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace RegexEditor
{
	public class NamedLock : IDisposable
	{
		#region Private Fields

		private static Dictionary<string, bool> _currentLocks = new Dictionary<string, bool>(StringComparer.InvariantCultureIgnoreCase);
		private string _name;

		#endregion

		#region Constructors

		public NamedLock(string name)
		{
			_name = name;
			_currentLocks[name] = true;
		}

		#endregion

		#region Public Members

		public static NamedLock AcquireLock(string name)
		{
			if (!IsLocked(name))
				return new NamedLock(name);

			return null;
		}

		public static NamedLock AcquireLock(string name, params string[] dependentLocks)
		{
			if (!IsLocked(name))
			{
				if (!dependentLocks.Any(l => IsLocked(l)))
					return new NamedLock(name);
			}

			return null;
		}

		public static bool IsLocked(string name)
		{
			if (_currentLocks.ContainsKey(name))
				return _currentLocks[name];

			return false;
		}

		public void Dispose()
		{
			_currentLocks[_name] = false;
		}

		#endregion
	}
}
